<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb :routes="routes">
        <template slot="itemRender" slot-scope="{ route, routes, paths }">
          <span v-if="routes.indexOf(route) === routes.length - 1">{{ route.breadcrumbName }}</span>
          <router-link v-else :to="`${basePath}/${paths.join('/')}`">{{ route.breadcrumbName }}</router-link>
        </template>
      </a-breadcrumb>
    </div>
    <div class="pageContentWhole">
      <a-form-model
        ref="form"
        :rules="rules"
        :model="form"
        :label-col="{span:2}"
        :wrapper-col="{span:10}"
        style="margin-top:20px"
      >
        <a-form-model-item label="结算对象" prop="custId">
          <a-select
            show-search
            :show-arrow="false"
            :filter-option="false"
            :default-active-first-option="false"
            :not-found-content="null"
            v-model="form.custId"
            @search="onSearch"
          >
            <a-select-option v-for="d in custList" :key="d.id">{{ d.name }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="上传数据" :wrapper-col="{span:14}">
          <a-row>
            <a-col :span="17">
              <a-upload-dragger
                accept=".xls, .xlsx"
                :action="uploadUrl"
                :headers="headers"
                :beforeUpload="beforeUpload"
                :file-list="fileList"
                @change="handleChange"
              >
                <p class="ant-upload-drag-icon">
                  <a-icon type="inbox" />
                </p>
                <p class="ant-upload-text">上传Excel文件</p>
              </a-upload-dragger>
            </a-col>
            <a-col :span="3" :offset="1">
              <a-button ghost type="primary" @click="download" style="margin-top:95px">下载模板</a-button>
            </a-col>
            <a-col :span="2" :offset="1" style="margin-top:90px">
              <a-tooltip placement="rightTop">
                <template slot="title">
                  <div>1、上传的Excel中，第一列必须为运单号</div>
                  <div>2、第二列必须为费用金额</div>
                  <div>3、第三列及之后的列不做处理</div>
                </template>
                <a>
                  <a-icon type="info-circle" style="margin-right:5px" />说明
                </a>
              </a-tooltip>
            </a-col>
          </a-row>
        </a-form-model-item>
        <a-form-model-item label="对账结果" :wrapper-col="{span:14}">
          <a-row>
            <a-col :span="17">
              <a-list size="large" bordered>
                <a-list-item>
                  账单总金额
                  <span class="orange">{{billInfo.totalAmount}}</span>
                </a-list-item>
                <a-list-item>
                  对账匹配成功
                  <span class="orange">{{billInfo.successNum}}</span>条费用明细，涉及金额
                  <span class="orange">{{billInfo.successAmount}}</span>
                </a-list-item>
                <a-list-item>
                  存在
                  <span class="orange">{{billInfo.failNum}}</span>条记录对账失败，涉及金额
                  <span class="orange">{{billInfo.failAmount}}</span>
                </a-list-item>
              </a-list>
            </a-col>
            <a-col :span="6" :offset="1">
              <a-button type="primary" style="margin-top:128px" @click="resultExport">导出结果</a-button>
            </a-col>
          </a-row>
        </a-form-model-item>
      </a-form-model>
      <div class="btnGroup">
        <div class="btnItem">
          <a-button type="primary" @click="generateBill">生成新对账单</a-button>
        </div>
        <div class="btnItem">
          <a-button class="btnItem" type="primary" @click="addToBill">合并到现有账单</a-button>
        </div>
        <div class="btnItem">
          <a-button class="btnItem" type="primary" @click="resetPage" ghost>重 置</a-button>
        </div>
      </div>
      <!-- <div class="dataSource">
        <a-list v-if="data.length===0" />
        <a-table
          v-else
          :columns="columns"
          :loading="loading"
          :data-source="data"
          style="margin-top:25px;"
          :scroll="{x:2600,y:450}"
          :pagination="false"
          :row-class-name="record => record.canImport===1 ? '' : 'redRow'"
          :row-key="(record,index) => index"
        >
          <template slot="status" slot-scope="record">
            <span v-if="record.containerStatus === 'A'">A</span>
            <span v-else-if="record.containerStatus === 'COMMON'">普通</span>
            <span v-else-if="record.containerStatus === 'BROKEN'">坏箱</span>
            <span v-else-if="record.containerStatus === 'DIRTY'">污箱</span>
          </template>
        </a-table>
      </div>-->
    </div>

    <!-- 生成账单 -->
    <a-modal
      :visible="generateVisible"
      title="确认生成账单"
      centered
      :destroyOnClose="true"
      :maskClosable="false"
      :confirmLoading="confirmLoading"
      @ok="handleOk2"
      @cancel="handleCancel2"
    >
      <a-form-model
        ref="rulesForm"
        :model="generateForm"
        :rules="rules"
        :labelCol="{span: 8}"
        :wrapperCol="{span: 14}"
      >
        <a-form-model-item label="收款单位">
          <router-link :to="`/supplierCenter/receivableSettlementObject/${custId}`">{{customName}}</router-link>
        </a-form-model-item>
        <a-form-model-item label="账期截止日期" prop="endDate">
          <a-date-picker @change="onChangeEndDate">
            <a-icon slot="suffixIcon" type="calendar" />
          </a-date-picker>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 添加到账单 -->
    <addToBillModal
      :visible="addToVisible"
      :billCostIds="billCostIds"
      :cc="cc"
      @setVisible="setAddToMadal"
    />
  </div>
</template>
<script>
import addToBillModal from '@/page/financialCenter/addToBillModal'
import { commonExport } from '@/api/request'
import { queryCustNameList } from '@/api'
import {createBill} from '@/api/financialCenter'
import { VERSION_NO, APP_KEY, REQUEST_INTEFACE_URL } from '@/common/config'
import md5 from 'md5'
import store from 'store'
import Util from '@/common/util'
// import reqwest from 'reqwest'
import _ from 'lodash/debounce'
const columns = [
  {
    title: '序号',
    width: 80,
    customRender: (text, record, index) => {
      return index + 1
    }
  },
  {
    title: '箱号',
    dataIndex: 'containerNo'
  },
  {
    title: '封号',
    customRender: (text, record, index) => {
      return record.containerSealNo ? record.containerSealNo : '--'
    }
  },
  {
    title: '运单号',
    width: 150,
    customRender: (text, record, index) => {
      return record.seagoingShipOrderCode
        ? record.seagoingShipOrderCode
        : '--'
    }
  },
  {
    title: '是否调空箱入场',
    width: 150,
    customRender: (text, record, index) => {
      return record.enterIsEmpty === 1 ? '是' : '否'
    }
  },
  {
    title: '箱型',
    dataIndex: 'containerType'
  },
  {
    title: '持箱人',
    dataIndex: 'holder',
    width: 260
  },
  {
    title: '箱属',
    dataIndex: 'containerBelong'
  },
  {
    title: '箱况',
    scopedSlots: {
      customRender: 'status'
    }
  },
  {
    title: '箱态',
    customRender: (text, record, index) => {
      return record.emptyOrHeavy === 1 ? '空' : '重'
    }
  },
  {
    title: '货名',
    customRender: (text, record, index) => {
      return record.goodsName ? record.goodsName : '--'
    }
  },
  {
    title: '货重（吨）',
    customRender: (text, record, index) => {
      return record.goodsWeight ? record.goodsWeight : '--'
    }
  },
  {
    title: '所在港口',
    dataIndex: 'portName'
  },
  {
    title: '始发港',
    customRender: (text, record, index) => {
      return record.startPortName ? record.startPortName : '--'
    }
  },
  {
    title: '目的港',
    customRender: (text, record, index) => {
      return record.endPortName ? record.endPortName : '--'
    }
  },
  {
    title: '船名/航次',
    width: 180,
    dataIndex: 'voyage'
  },
  {
    title: '卸船日期',
    width: 150,
    customRender: (text, record, index) => {
      return record.enterTime ? record.enterTime : '--'
    }
  },
  {
    title: '装卸费（元）',
    width: 150,
    customRender: (text, record, index) => {
      return record.enterHandlingFee ? record.enterHandlingFee : '--'
    }
  },
  {
    title: '备注',
    width: 150,
    customRender: (text, record, index) => {
      return record.remark ? record.remark : '--'
    }
  }
]
const formMessage = `必填项不能为空`
export default {
  data () {
    this.onSearch = _(this.onSearch, 800)
    return {
      basePath: '/financialCenter',
      routes: [
        {
          path: '/payableDetailOfHuaJzx',
          breadcrumbName: '应付明细'
        },
        {
          path: '',
          breadcrumbName: '自动对账'
        }
      ],
      fileList: [],
      previewVisible: false,
      previewImage: '',
      loading: false,
      headers: {},
      file: {},
      uploadUrl: REQUEST_INTEFACE_URL + '/bill/autoCheckAccount',
      columns,
      data: [],
      useableNumber: 0,
      form: {
        custId: ''
      },
      rules: {
        custId: [
          { required: true, message: formMessage, trigger: ['blur', 'change'] }
        ]
      },
      custList: [],
      billInfo: {
        totalAmount: 0,
        successNum: 0,
        successAmount: 0,
        failNum: 0,
        failAmount: 0,
        billCostIds: []
      },
      // 生成账单
      generateVisible: false,
      customName: '',
      custId: '',
      generateForm: {
        endDate: null
      },
      rules1: {
        endDate: [{required: true, message: formMessage, trigger: ['blur', 'change']}]
      },
      confirmLoading: false,
      // 添加到账单
      addToVisible: false,
      billCostIds: [],
      cc: {},
      temData: {}
    }
  },
  components: {
    addToBillModal
  },
  methods: {
    downloadRequest () {
      commonExport('/common/downloadExcelTemplate', {
        name: '自动对账导入模板.xls'
      })
    },
    beforeUpload (file) {
      let self = this
      let fileLength = self.fileList.length
      let custId = self.form.custId
      return new Promise((resolve, reject) => {
        if (custId) {
          if (fileLength > 0) {
            self.$message.error('Excel文件已存在！')
            reject(new Error(false))
          } else {
            const uuid = Util.getUUID()
            const headers = {
              appKey: APP_KEY,
              version: VERSION_NO,
              timestamp: (() => new Date().getTime())(),
              nonce: uuid,
              token: store.get('token') ? store.get('token') : '',
              sign: md5(`appKey${APP_KEY}nonce${uuid}timestamp${new Date().getTime()}84001ac0d7064aea883e8f6623ceb82b`).toUpperCase(),
              custId: custId
            }
            self.headers = headers
            resolve()
          }
        } else {
          self.$message.error(formMessage)
          reject(new Error(false))
        }
      })
    },
    handleChange ({ file, fileList }) {
      this.fileList = fileList
      this.file = file
      if (file.status === 'done') {
        this.billInfo = file.response.data.rsp
        this.temData = file.response.data
        // console.log(file.response.data)
      } else if (file.status === 'removed') {
        this.data = []
        this.useableNumber = 0
      }
    },
    resultExport () {
      // if (this.data.length === 0) {
      //   this.$message.error('匹配失败！')
      //   return false
      // }
      // let _self = this
      // const formData = new FormData()
      // const fileUrl = REQUEST_INTEFACE_URL + '/bill/exportCheckResult'
      // formData.append('file', _self.file.originFileObj)
      // const uuid = Util.getUUID()
      // reqwest({
      //   url: fileUrl,
      //   method: 'post',
      //   headers: {
      //     appKey: APP_KEY,
      //     version: VERSION_NO,
      //     timestamp: (() => new Date().getTime())(),
      //     nonce: uuid,
      //     token: store.get('token') ? store.get('token') : '',
      //     sign: md5(`appKey${APP_KEY}nonce${uuid}timestamp${new Date().getTime()}84001ac0d7064aea883e8f6623ceb82b`).toUpperCase(),
      //     custId: _self.form.custId
      //   },
      //   processData: false,
      //   data: formData,
      //   success: response => {
      //     if (response.status === 200) {
      //       // console.log(response)
      //       let blob = new Blob([response.response], {type: 'application/vnd.ms-excel;charset=utf-8'})
      //       let downloadElement = document.createElement('a')
      //       let href = window.URL.createObjectURL(blob) // 创建下载的链接
      //       downloadElement.href = href
      //       // 获取文件名
      //       let fileName = '对账excel' + new Date().getTime()
      //       downloadElement.download = fileName
      //       document.body.appendChild(downloadElement)
      //       downloadElement.click() // 点击下载
      //       document.body.removeChild(downloadElement) // 下载完成移除元素
      //       window.URL.revokeObjectURL(href) // 释放掉blob对象
      //     } else {
      //       _self.$message.error('导出失败')
      //     }
      //   },
      //   error: () => {
      //     _self.$message.error('文件上传失败！')
      //   }
      // })
      let param = {}
      param = this.temData
      delete param.rsp
      // console.log(JSON.stringify(param))
      commonExport('/bill/exportCheckResult', param)
    },
    download () {
      this.downloadRequest()
    },
    custListRequest (e) {
      queryCustNameList(e)
        .then(res => {
          this.custList = res.data
        })
        .catch(rs => {})
    },
    onSearch (searchText) {
      let param = {
        nameLike: searchText,
        belongCompany: 'JIA_HUA',
        custTypeLike: 'SUPPLIER',
        status: 1,
        isPayable: 1
      }
      this.custListRequest(param)
    },
    resetPage () {
      this.form.custId = ''
      this.data = []
      this.useableNumber = 0
      this.custList = []
      this.fileList = []
      this.billInfo = {
        totalAmount: 0,
        successNum: 0,
        successAmount: 0,
        failNum: 0,
        failAmount: 0,
        billCostIds: []
      }
    },
    onChangeEndDate (date, dataStr) {
      this.generateForm.endDate = dataStr
    },
    checkBills () {
      const t = this.custList.filter(v => this.form.custId === v.id)[0]
      if (!t) {
        this.$message.error('请选择结算对象')
        return false
      }

      if (this.billInfo.billCostIds.length === 0) {
        this.$message.error('至少匹配到一个应付明细')
        return false
      }

      return true
    },
    generateBill () {
      if (!this.$root._bc.createBill) {
        this.$message.error('您无此权限！')
        return
      }
      if (this.checkBills()) {
        this.customName = this.custList.filter(v => this.form.custId === v.id)[0].name
        this.custId = this.custList.filter(v => this.form.custId === v.id)[0].id
        this.generateVisible = true
      }
    },
    handleOk2 () { // 生成账单
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          createBill({
            billCostIds: this.billInfo.billCostIds,
            ...this.generateForm
          }).then(rsp => {
            this.$message.success('生成账单成功')
            this.confirmLoading = false
            this.generateVisible = false
            this.resetPage()
          }).catch(() => { this.confirmLoading = false })
        }
      })
    },
    handleCancel2 () {
      this.generateVisible = false
    },
    addToBill () { // 添加到账单
      if (!this.$root._bc.addToBill) {
        this.$message.error('您无此权限！')
        return
      }
      if (this.checkBills()) {
        this.billCostIds = this.billInfo.billCostIds
        const target = this.custList.filter(v => this.form.custId === v.id)[0]
        this.cc = {
          custName: target.custName,
          currencyType: target.currencyType,
          businessType: 'JIA_HUA_ORDER',
          feeType: 2
        }
        this.addToVisible = true
      }
    },
    setAddToMadal (f) {
      if (f) {
        this.$message.success('添加到账单成功')
        this.resetPage()
      }
      this.addToVisible = false
    }
  },
  mounted () {
    this.custListRequest({
      name: '',
      belongCompany: 'JIA_HUA',
      custTypeLike: 'SUPPLIER',
      status: 1,
      isPayable: 1
    })
  }
}
</script>

<style>
.btnGroup {
  width: 500px;
  margin: 50px auto;
  display: flex;
}
.btnGroup .btnItem {
  flex: 1;
}
.orange {
  color: orange;
}
</style>
